package com.zjdiepu.www.diepu.api;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.diepu.www.client.proxy.partner.request.own.DiepuZxCopyApplyRequest;
import com.diepu.www.client.proxy.partner.request.own.DiepuZxQuerySuccessBusiIdUpRequest;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.diepu.enums.ModeIDTypeDiepu;
import com.zjdiepu.www.diepu.enums.TransferStatusDiepu;
import com.zjdiepu.www.enums.StatusAttachments;
import com.zjdiepu.www.enums.TransferModeID;
import com.zjdiepu.www.proxy.biz.own.HzBiz;
import com.zjdiepu.www.proxy.biz.own.HzGhBiz;
import com.zjdiepu.www.proxy.biz.own.LogsBiz;
import com.zjdiepu.www.proxy.model.dto.own.SysUserProxy;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferLogs;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferLogsSub;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOrdernoBank;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferZxCreditQuery;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferZxQueryCreditApply;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferZxQueryCreditApplySub;
import com.zjdiepu.www.response.BaseResponse;
import com.zjdiepu.www.response.BooleanResponse;
import com.zjdiepu.www.security.server.convert.MyJson;
import com.zjdiepu.www.security.server.core.Partners;
import com.zjdiepu.www.security.server.interceptor.PartnerProvider;

@MyJson
@RestController
@RequestMapping(value="OwnDiepuController", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
@PartnerProvider(partner = Partners.DIE_PU)
public class OwnDiepuController 
{
	//这是稻普调中间服务器

	@Resource
	private HzGhBiz hzGhBiz;
	
	@Resource
	private LogsBiz logsBiz;
	
	@Resource
	private HzBiz hzBiz;

	/**
	 * 征信反馈修改业务编号
	 * 主程序征信反馈成功才会回调
	 * @param diepuZxQuerySuccessBusiIdUpRequest
	 * @return
	 */
	@RequestMapping(value="diepuZxQuerySuccessBusiIdUp",method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public BaseResponse<BooleanResponse> diepuZxQuerySuccessBusiIdUp(@Validated @RequestBody DiepuZxQuerySuccessBusiIdUpRequest diepuZxQuerySuccessBusiIdUpRequest) 
	{
		try 
		{
			if(null == diepuZxQuerySuccessBusiIdUpRequest)
			{
				TransferLogs transferLogs = new TransferLogs();
				transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
				transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
				transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
				transferLogs.setDescribeEvent(ResultFlagType.PARAM_EMPTY.getValue());
				logsBiz.diepuLogs(null, transferLogs, null);
				hzBiz.loggerError(ResultFlagType.PARAM_EMPTY.getValue());
				throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
			}
			
			TransferZxQueryCreditApply transferZxQueryCreditApply = new TransferZxQueryCreditApply();
			transferZxQueryCreditApply.setId(diepuZxQuerySuccessBusiIdUpRequest.getId());
			transferZxQueryCreditApply.setBusiId(diepuZxQuerySuccessBusiIdUpRequest.getBusiId());
			
			SysUserProxy sysUserProxy = new SysUserProxy();
			sysUserProxy.setUserId(TransferModeID.FKZXJG.getCode());
			sysUserProxy.setLoginName(TransferModeID.FKZXJG.getValue());
			int count = hzGhBiz.diepuZxQuerySuccessBusiIdUp(sysUserProxy, transferZxQueryCreditApply);
			if(count < 1)
			{
				return BaseResponse.successWithBoolean(false);
			}
		} 
		catch (Exception e) 
		{
			
			TransferLogs transferLogs = new TransferLogs();
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.FKZXJG.getCode());
			transferLogs.setTransferModeName(TransferModeID.FKZXJG.getValue());
			transferLogs.setDescribeEvent("diepuZxQuerySuccessBusiIdUp Exception e ");
			logsBiz.diepuLogs(null, transferLogs, null);
			hzBiz.loggerError("diepuZxQuerySuccessBusiIdUp Exception e "+e.getMessage());
			return BaseResponse.successWithBoolean(false);
		}
		return BaseResponse.successWithBoolean(true);
	}
	
	
	/**
	 * 内勤或者业务员提交查征信后，主程序同时将相应信息发送到该接口。
	 * 入参：征信申请主表对象、征信申请子表对象（可能有多个）、征信查询结果对象（工行版）（可能有多个）
	 * 出参：处理结果（成功：0  ； 异常  01xxxx）
	 * 1、将征信主表对象和子表对象写入 transfer_zx_query_credit_apply 和 transfer_zx_query_credit_apply_sub （type_data =3）
	 * 2、将征信查询结果对象（工行版）写入征信查询结果对象（工行版）（type_data =3；transfer_handle_status = 10）
	 * 3、写一个时间为5分钟（可配）之后的下载附件定时任务；  张郑健
	 * 4、写一个时间为10分钟（可配）之后的向工行申请查征信定时任务  张郑健
	 * @param diepuZxCopyApplyRequest
	 * @return
	 */
	@RequestMapping(value = "diepuZxCopyApply", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public BaseResponse<BooleanResponse> diepuZxCopyApply(
			@Validated @RequestBody DiepuZxCopyApplyRequest diepuZxCopyApplyRequest) {
		String userId = Optional.ofNullable(diepuZxCopyApplyRequest)
				.map(item -> item.getLoginName())
				.orElse(SystemConsts.DEFAULT_ID);
		String loginName = Optional.ofNullable(diepuZxCopyApplyRequest)
				.map(item -> item.getLoginName()).orElse("碟普程序向中转服务器申请查征信");
		String description = null;
		SysUserProxy sysUserProxy = new SysUserProxy();
		sysUserProxy.setUserId(userId);
		sysUserProxy.setLoginName(loginName);
		BaseResponse<BooleanResponse> response = null;
		try {
			if (StringUtils.isBlank(userId) || StringUtils.isBlank(loginName)) {
				description = ResultFlagType.LOGIN_TIMEOUT.getValue();
				throw new BaseException(ResultFlagType.LOGIN_TIMEOUT.getCode().toString(), ResultFlagType.LOGIN_TIMEOUT.getValue());
			}

			if (null == diepuZxCopyApplyRequest.transferZxQueryCreditApply) {
				description = "diepuZxCopyApplyRequest transferZxQueryCreditApply is null";
				throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), "diepuZxCopyApplyRequest transferZxQueryCreditApply is null");
			}

			if (CollectionUtils .isEmpty(diepuZxCopyApplyRequest.transferZxQueryCreditApplySubs)) {
				description = "diepuZxCopyApplyRequest transferZxQueryCreditApplySub is null";
				throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), "diepuZxCopyApplyRequest transferZxQueryCreditApplySub is null");
			}

			if (CollectionUtils .isEmpty(diepuZxCopyApplyRequest.transCreditQueryHzicbcs)) {
				description = "diepuZxCopyApplyRequest transCreditQueryHzicbcs is null";
				throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), "diepuZxCopyApplyRequest transCreditQueryHzicbcs is null");
			}

			if (null == diepuZxCopyApplyRequest.transYwOrdernoBank) {
				description = "diepuZxCopyApplyRequest transYwOrdernoBank is null";
				throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(), "diepuZxCopyApplyRequest transYwOrdernoBank is null");
			}

			TransferZxQueryCreditApply transferZxQueryCreditApply = new TransferZxQueryCreditApply();
			BeanUtils.copyProperties( diepuZxCopyApplyRequest.transferZxQueryCreditApply, transferZxQueryCreditApply);
			transferZxQueryCreditApply.setTransferHandleStatus(Integer.valueOf(TransferStatusDiepu.JSCG.getCode()));

			List<TransferZxQueryCreditApplySub> transferZxQueryCreditApplySub = new ArrayList<TransferZxQueryCreditApplySub>();
			for (int i = 0; i < diepuZxCopyApplyRequest.transferZxQueryCreditApplySubs.size(); i++) {
				TransferZxQueryCreditApplySub queryCreditApplySub = new TransferZxQueryCreditApplySub();
				BeanUtils.copyProperties( diepuZxCopyApplyRequest.transferZxQueryCreditApplySubs.get(i), queryCreditApplySub);
				queryCreditApplySub.setStatusAttachments(StatusAttachments.STATUSATTACHMENTS10.getCode().toString());
				transferZxQueryCreditApplySub.add(queryCreditApplySub);
			}

			List<TransferZxCreditQuery> transferCreditQueryHzicbcs = new ArrayList<TransferZxCreditQuery>();
			for (int i = 0; i < diepuZxCopyApplyRequest.transCreditQueryHzicbcs.size(); i++) {
				TransferZxCreditQuery transferCreditQueryHzicbc = new TransferZxCreditQuery();
				BeanUtils.copyProperties(diepuZxCopyApplyRequest.transCreditQueryHzicbcs.get(i),transferCreditQueryHzicbc);
				transferCreditQueryHzicbcs.add(transferCreditQueryHzicbc);
			}

			TransferYwOrdernoBank transferYwOrdernoBank = new TransferYwOrdernoBank();
			BeanUtils.copyProperties(diepuZxCopyApplyRequest.transYwOrdernoBank, transferYwOrdernoBank);

			int count = hzGhBiz.diepuZxCopyApply(sysUserProxy, transferZxQueryCreditApply, transferZxQueryCreditApplySub, transferCreditQueryHzicbcs, transferYwOrdernoBank);
			if (count < 1) {
				response = BaseResponse.successWithBoolean(false);
				return response;
			}

			response = BaseResponse.successWithBoolean(true);
			return response;
		} catch (Exception e) {
			if (StringUtils.isEmpty(description)) {
				description = "diepuZxCopyApply Exception e " + e.getMessage();
			}
			hzBiz.loggerError("diepuZxCopyApply Exception e " + e.getMessage());
			response = BaseResponse.successWithBoolean(false);
			return response;
		} finally {
			TransferLogs transferLogs = new TransferLogs();
			String applyId = Optional.ofNullable(diepuZxCopyApplyRequest)
					.map(item -> item.getTransferZxQueryCreditApply())
					.map(item -> item.getId()).orElse(null);
			transferLogs.setDataId(applyId);
			String orderNo = Optional.ofNullable(diepuZxCopyApplyRequest)
					.map(item -> item.getTransYwOrdernoBank())
					.map(item -> item.getOrdeRno()).orElse(null);
			transferLogs.setBankOrderNo(orderNo);
			transferLogs.setBusiType(ModeIDTypeDiepu.HZICBC.getCode());
			transferLogs.setTransferModeId(TransferModeID.SQCZX.getCode());
			transferLogs.setTransferModeName(TransferModeID.SQCZX.getValue());
			transferLogs.setStatusEvent(Integer
					.valueOf(TransferStatusDiepu.STATUSEVENT1.getCode()));
			transferLogs.setDescribeEvent("碟普程序向中转服务器申请查征信成功");
			transferLogs.setRemarks(description);
			TransferLogsSub transferLogsSub = new TransferLogsSub();
			transferLogsSub.setDataId(applyId);
			transferLogsSub.setBankOrderNo(orderNo);
			transferLogsSub.setRequestMessageEvent(JSON
					.toJSONString(diepuZxCopyApplyRequest));
			transferLogsSub.setRequestMessageEventEncode(null);
			transferLogsSub
					.setResponseMessageEvent(JSON.toJSONString(response));
			transferLogsSub.setRemarks(description);
			logsBiz.diepuLogs(sysUserProxy, transferLogs, transferLogsSub);
		}
	}
	
}
